package com.yyfax.pay.config.data.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.yyfax.commons.json.JacksonUtil;
import com.yyfax.framework.common.Log;
import com.yyfax.framework.service.CacheService;
import com.yyfax.framework.service.impl.BaseServiceImpl;
import com.yyfax.framework.yyfax.enums.YesNoEnum;
import com.yyfax.pay.common.constants.CacheName;
import com.yyfax.pay.config.data.dao.MerchantPaymentDao;
import com.yyfax.pay.config.data.service.MerchantPaymentService;
import com.yyfax.pay.config.model.po.MerchantPaymentPO;

@Service
public class MerchantPaymentServiceImpl extends BaseServiceImpl implements MerchantPaymentService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private MerchantPaymentDao merchantPaymentDao;

	public MerchantPaymentServiceImpl(@Qualifier("payCacheService") CacheService cacheService) {
		super(cacheService);
	}

	@Override
	public int save(MerchantPaymentPO config) throws Exception {
		if (config == null) {
			logger.error("新增商户支付通道关系传入参数为空返回-1");
			return -1;
		}
		clearCache(CacheName.MERCHANT_PAYMENT);
		return merchantPaymentDao.insert(config);
	}

	@Override
	public int modify(MerchantPaymentPO config) throws Exception {
		if (config == null) {
			logger.error("修改商户支付通道关系传入参数为空返回-1");
			return -1;
		}
		// 更新商户信息刷新缓存
		clearCache(CacheName.MERCHANT_PAYMENT);
		return merchantPaymentDao.update(config);
	}

	@Override
	public MerchantPaymentPO queryById(int id) throws Exception {
		if (id <= 0) {
			logger.error("根据id查询商户支付通道关系传入id为{},id错误返回空", id);
			return null;
		}
		return merchantPaymentDao.selectById(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MerchantPaymentPO> queryForList() throws Exception {
		// 从缓存读取
		List<MerchantPaymentPO> pos = null;
		String json = getCache(CacheName.MERCHANT_PAYMENT);
		if (StringUtils.isNotBlank(json)) {
			pos = (List<MerchantPaymentPO>) JacksonUtil.fromJson(json, List.class, MerchantPaymentPO.class);
			return pos;
		}
		logger.info("缓存数据为空从数据库获取查询所有商户支付通道关系信息");
		pos = merchantPaymentDao.selectForList();
		if (pos != null && !pos.isEmpty()) {
			cacheService.set(CacheName.MERCHANT_PAYMENT, JacksonUtil.toJson(pos));
		}
		return pos;
	}

	@Override
	public MerchantPaymentPO queryByThirdMerchantCode(String merchantCode, String paymentCode, String payType, String payMode) throws Exception {
		if (StringUtils.isBlank(merchantCode) || StringUtils.isBlank(paymentCode) || StringUtils.isBlank(payType) || StringUtils.isBlank(payMode)) {
			logger.error("根据四要素查询商户支付通道关系传入参数有空值，merchantCode{}，paymentCode{}，payType{}，payMode{}", merchantCode, paymentCode, payType, payMode);
			return null;
		}

		String json = getCache(CacheName.MERCHANT_PAYMENT);
		if (StringUtils.isNotBlank(json)) {
			List<MerchantPaymentPO> list = (List<MerchantPaymentPO>) JacksonUtil.fromJson(json, List.class, MerchantPaymentPO.class);
			for (MerchantPaymentPO po : list) {
				if (merchantCode.equals(po.getMerchantCode()) && paymentCode.equals(po.getPaymentCode()) && payMode.equals(po.getPayMode())
						&& payType.equals(po.getPayType())) {
					return po;
				}
			}
		} else {
			queryForList();
		}

		logger.info("内存数据为空从数据库获取查询所有商户支付通道关系信息");
		return merchantPaymentDao.selectMerchantPayment(merchantCode, paymentCode, payType, payMode);
	}

	@Override
	public MerchantPaymentPO queryByThirdMerchantId(String payMerchantId, String paymentCode, String payType, String payMode) throws Exception {
		if (StringUtils.isBlank(payMerchantId) || StringUtils.isBlank(paymentCode) || StringUtils.isBlank(payType) || StringUtils.isBlank(payMode)) {
			logger.error("根据四要素查询商户支付通道关系传入参数有空值，payMerchantId{}，paymentCode{}，payType{}，payMode{}", payMerchantId, paymentCode, payType, payMode);
			return null;
		}
		// 从内存获取数据
		String json = getCache(CacheName.MERCHANT_PAYMENT);
		if (StringUtils.isNotBlank(json)) {
			List<MerchantPaymentPO> list = (List<MerchantPaymentPO>) JacksonUtil.fromJson(json, List.class, MerchantPaymentPO.class);
			for (MerchantPaymentPO po : list) {
				if (payMerchantId.equals(po.getPayMerchantId()) && paymentCode.equals(po.getPaymentCode()) && payMode.equals(po.getPayMode())
						&& payType.equals(po.getPayType())) {
					return po;
				}
			}
		} else {
			queryForList();
		}
		logger.info("内存数据为空从数据库获取查询所有商户支付通道关系信息");
		return merchantPaymentDao.selectMerchantPaymentId(payMerchantId, paymentCode, payType, payMode);
	}

	@Override
	public MerchantPaymentPO queryDefaultByMerchantCode(String merchantCode, String payType, String payMode, String apiType) throws Exception {
		if (StringUtils.isBlank(merchantCode) || StringUtils.isBlank(payType) || StringUtils.isBlank(payMode)) {
			logger.error("根据四要素查询商户支付通道关系传入参数有空值，merchantCode{}，payType{}，payMode{}", merchantCode, payType, payMode);
			return null;
		}
		String json = getCache(CacheName.MERCHANT_PAYMENT);
		List<MerchantPaymentPO> list = null;
		if (StringUtils.isBlank(json)) {
			// 如果缓存不存在
			list = queryForList();
		} else {
			list = (List<MerchantPaymentPO>) JacksonUtil.fromJson(json, List.class, MerchantPaymentPO.class);
		}

		List<MerchantPaymentPO> apiList = new ArrayList<MerchantPaymentPO>();
		Integer maxLevel = 0;
		for (MerchantPaymentPO po : list) {
			if (merchantCode.equals(po.getMerchantCode()) && payType.equals(po.getPayType()) && payMode.equals(po.getPayMode())
					&& YesNoEnum.YES.isValue(po.getState())) {

				if (StringUtils.isNotBlank(apiType) && !apiType.equals(po.getApiType())) {
					// 如果apiType不为空,且apiType不匹配，则继续迭代
					continue;
				}

				if (maxLevel < po.getPriority()) {
					// 取最高优先级
					maxLevel = po.getPriority();
				}

				// 将满足条件的支付通道配置信息放到集合里
				apiList.add(po);
			}
		}

		for (MerchantPaymentPO vo : apiList) {
			if (maxLevel.equals(vo.getPriority())) {
				return vo;
			}
		}

		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MerchantPaymentPO> queryList(String merchantCode, String payType) throws Exception {
		if (StringUtils.isBlank(merchantCode) || StringUtils.isBlank(payType)) {
			logger.debug("查询商户支付通道配置信息，请求参数为空，merchantCode:{},payType:{}", merchantCode, payType);
			return null;
		}

		String json = getCache(CacheName.MERCHANT_PAYMENT);
		if (StringUtils.isNotBlank(json)) {
			List<MerchantPaymentPO> list = (List<MerchantPaymentPO>) JacksonUtil.fromJson(json, List.class, MerchantPaymentPO.class);
			List<MerchantPaymentPO> merchantPaymentList = new ArrayList<MerchantPaymentPO>();
			for (MerchantPaymentPO po : list) {
				if (merchantCode.equals(po.getMerchantCode()) && payType.equals(po.getPayType())) {
					merchantPaymentList.add(po);
				}
			}
			if (!merchantPaymentList.isEmpty() && merchantPaymentList != null) {
				return merchantPaymentList;
			}
		} else {
			queryForList();
		}
		logger.info("缓存数据为空从数据库获取查询所有商户支付通道关系信息");
		return merchantPaymentDao.selectListByMerchantAndPayType(merchantCode, payType);
	}

	@Override
	public <T> T queryByThirdMerchantCodeForExt(String merchantCode, String paymentCode, String payType, String payMode, Class<T> clazz)
			throws Exception {
		MerchantPaymentPO merchant = queryByThirdMerchantCode(merchantCode, paymentCode, payType, payMode);
		if (merchant == null || StringUtils.isBlank(merchant.getExt())) {
			logger.warn(Log.op("MerchantPaymentServiceImpl.queryByThirdMerchantCodeForExt").msg("merchantPayment缺少配置")
					.kv("merchantCode", merchantCode).kv("paymentCode", paymentCode).kv("payType", payType).kv("payMode", payMode).toString());
			return null;
		}

		return JacksonUtil.nonullMapper.fromJson(merchant.getExt(), clazz);
	}
}
